package com.rz.htk.finance.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rz.core.kit.RedisKit;
import com.rz.htk.config.RedisKeyConfig;
import com.rz.htk.finance.entity.ExchangeRate;
import com.rz.htk.finance.service.IExchangeRateService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author maweiyue
 * @Date 2019/8/13
 * @Description
 */
@Component
public class RefreshExchangeRateTask {
    @Resource
    private RedisKit redisKit;
    @Resource
    private IExchangeRateService exchangeRateService;

    @Scheduled(cron = "0 0/1 21 ? * MON-FRI")
    private void configureTasks() {
        try {
            URL urlObject = new URL("http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/ccpr.json?t");
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String inputLine = null;
            StringBuilder json = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            JSONObject jsonObject = JSONObject.parseObject(json.toString());
            String updateTime = jsonObject.getJSONObject("data").getString("lastDate");
            JSONArray array = jsonObject.getJSONArray("records");
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                String key = obj.getString("vrtEName");
                ExchangeRate rate = this.exchangeRateService.getByKey(key);
                if (rate == null) {
                    rate = new ExchangeRate();
                    rate.setEname(key);
                    rate.setName(obj.getString("vrtName"));
                }
                rate.setPrice(obj.getDouble("price"));
                rate.setUpdateTime(updateTime);
                boolean isOK = exchangeRateService.saveOrUpdate(rate);
                if (isOK) {
                    redisKit.setValue(RedisKeyConfig.getExchangeRateKey(key), obj.get("price"), 0);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
